package raytracer.misc;

import java.io.*;
import java.util.regex.*;
import raytracer.math.*;
import java.util.*;
import raytracer.objects.Triangle;

/**
 * The regular expressions have mostly been taken from MW's reader
 * @author Thorsten Roth
 *
 */
public class ObjReader {
	
	private static Pattern patVertices,patNorms,patFaces;
	private List<Vector3d> vertices,normals;
	private List<Triangle> triangles;
	
	static {						
		patVertices=Pattern.compile("v\\s+(-?\\d+\\.\\d+)\\s+(-?\\d+\\.\\d+)\\s+(-?\\d+\\.\\d+)");
		patNorms=Pattern.compile("vn\\s(-?\\d+.\\d+)\\s(-?\\d+.\\d+)\\s(-?\\d+.\\d+)");
		patFaces=Pattern.compile("f\\s+(\\d+)\\s*(\\d+)\\s*(\\d+)\\s*");
	}
	
	public ObjReader(String filename) {
		vertices=new ArrayList<Vector3d>();
		normals=new ArrayList<Vector3d>();
		triangles=new ArrayList<Triangle>();
		
		try {
			BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
			System.out.println("Reading "+filename+"...");
			Matcher matVertices,matNorms,matFaces;
			String curLine;
			
			while ((curLine=br.readLine())!=null) {
			
				matVertices=patVertices.matcher(curLine);
				while (matVertices.find()) {
					vertices.add(new Vector3d(
							Double.valueOf(matVertices.group(1)),
							Double.valueOf(matVertices.group(2)),
							Double.valueOf(matVertices.group(3))
					));
				}
				matNorms=patNorms.matcher(curLine);
				while (matNorms.find()) {
					normals.add(new Vector3d(
							Double.valueOf(matVertices.group(1)),
							Double.valueOf(matVertices.group(2)),
							Double.valueOf(matVertices.group(3))
					));
				}
				matFaces=patFaces.matcher(curLine);
				while (matFaces.find()) {
					triangles.add(new Triangle(
							new Vector3d(vertices.get(Integer.valueOf(matFaces.group(1))-1)),
							new Vector3d(vertices.get(Integer.valueOf(matFaces.group(2))-1)),
							new Vector3d(vertices.get(Integer.valueOf(matFaces.group(3))-1))
					));
				}
			}
		}
		catch (FileNotFoundException e) {
			System.out.println("File "+filename+" could not be found!");
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public List<Triangle> getTriangles() {
		return this.triangles;
	}
	
}